package com.yunst.execute.impl;

import com.yunst.execute.ExecuteOperation;
import com.yunst.net.message.ImageMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author yunst
 * @date 2022/12/29
 */
public class ExecuteTask extends Thread {
    private ChannelHandlerContext channelHandlerContext;

    public ExecuteTask(ChannelHandlerContext channelHandlerContext) {
        this.channelHandlerContext = channelHandlerContext;

    }

    private volatile static Boolean isStart = true;
    private ExecuteOperation<BufferedImage> operation = new ScreenShotExecute();

    public static void stopRun() {
        isStart = false;
    }

    @Override
    public void run() {
        isStart = true;
        while (isStart) {
            try {
                BufferedImage image = operation.execute();
                ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", byteOutputStream);
                byte[] bytes = byteOutputStream.toByteArray();
                sendData(bytes);
                Thread.sleep(40);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    private void sendData(byte[] bytes) {
        ImageMessage imageMessage = new ImageMessage();
        imageMessage.setLen(bytes.length);
        imageMessage.setContent(bytes);
        channelHandlerContext.writeAndFlush(imageMessage);
    }
}
